package net.qqxh.sunflow.server.office.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.qqxh.common.ossclient.FolderType;
import net.qqxh.common.ossclient.MagicOssClient;
import net.qqxh.sunflow.server.common.BaseController;
import net.qqxh.sunflow.server.office.bean.OfficeFile;
import net.qqxh.sunflow.server.office.service.OfficeFileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Scanner;

/**
 * Copyright (C), 2019-2020, sunflow开发团队
 * 在线编辑文件 前端控制器
 *
 * @author cjy
 * @fileName OfficeFileController.java
 * @date 2019/5/25 10:22
 */
@RestController
@RequestMapping("/office")
public class OfficeFileController extends BaseController {
    @Autowired
    OfficeFileService officeFileService;

    @Autowired
    private MagicOssClient magicOssClient;

    /**
     * 在线编辑文件 列表
     *
     * @param request {@link HttpServletRequest}
     * @param current 页码
     * @param size    每页条数
     * @return 数据字典目录列表Json
     * @author cjy
     * @date 2019/5/25 10:25
     */
    @RequestMapping("/list")
    public Object list(HttpServletRequest request, int current, int size) {
        QueryWrapper<OfficeFile> queryWrapper = new QueryWrapper<OfficeFile>();
        queryWrapper.eq("creator", getLoginUser().getId());
        String fileName = request.getParameter("fileName");
        if (StringUtils.isNotBlank(fileName)) {
            queryWrapper.like("file_name", fileName);
        }
        Page<OfficeFile> page = new Page<OfficeFile>(current, size);
        return responseSuccess(officeFileService.page(page, queryWrapper));
    }

    /**
     * 创建
     *
     * @param
     * @return
     * @author cjy
     * @date 2019/5/25 16:05
     */
    @PostMapping("/create")
    public Object uploadOffice(OfficeFile officeFile) {
        Date date = new Date();
        officeFile.setCreator(getLoginUser().getId());
        officeFile.setCreateDate(date);
        return responseSuccess(officeFileService.save(officeFile));
    }

    /**
     * 删除
     *
     * @param fileId 文件编码
     * @return 是否成功
     * @author cjy
     * @date 2019/5/25 16:05
     */
    @DeleteMapping("/delete/{fileId}")
    public Object delete(@PathVariable String fileId) {
        return responseSuccess(officeFileService.removeById(fileId));
    }


    /**
     * onlyOffice在线编辑保存后回调，更新oss文件
     *
     * @param
     * @return
     * @author cjy
     * @date 2019/5/25 16:05
     */
    @PostMapping("/onlyoffice/save/{fileId}")
    public void onlyofficeSave(@PathVariable String fileId, HttpServletRequest request, HttpServletResponse response) {
        try {
            PrintWriter writer = response.getWriter();
            String body = "";
            try {
                Scanner scanner = new Scanner(request.getInputStream());
                scanner.useDelimiter("\\A");
                body = scanner.hasNext() ? scanner.next() : "";
                scanner.close();
            } catch (Exception ex) {
                writer.write("get request.getInputStream error:" + ex.getMessage());
                return;
            }
            if (body.isEmpty()) {
                writer.write("empty request.getInputStream");
                return;
            }

            JSONObject jsonObj = JSON.parseObject(body);

            int status = (Integer) jsonObj.get("status");

            int saved = 0;
            if (status == 2 || status == 3) //MustSave, Corrupted
            {
                String downloadUri = (String) jsonObj.get("url");

                try {
                    URL url = new URL(downloadUri);
                    java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                    InputStream stream = connection.getInputStream();

                    if (stream == null) {
                        throw new Exception("Stream is null");
                    }

                    OfficeFile officeFile = officeFileService.getById(fileId);
                    if(officeFile != null) {
                        String ossUrl = magicOssClient.upload("sunflow", "office", FolderType.yyyyMMdd, stream, officeFile.getFileExtension());
                        officeFile.setFileUrl(ossUrl);
                        officeFileService.updateById(officeFile);
                    }

                    connection.disconnect();
                } catch (Exception ex) {
                    saved = 1;
                    ex.printStackTrace();
                }

            }
            writer.write("{\"error\":" + saved + "}");
        } catch (IOException e) {
//            writer.write("{\"error\":-1}");
            e.printStackTrace();
        }
    }
}
